package cn.itcast.order.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.RequestOriginParser;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 1.在gateway服务中的application.yml中新增：
 * - AddRequestHeader=origin,gateway #添加名为origin的请求头,值为gateway
 *
 * 2.以下代码获取请求头中的参数origin
 *
 * 3.在sentinel中http://localhost:8090/对 /order/{orderId},点击授权，填写gateway
 *
 * 4.如果直接访问http://localhost:8081/order/101,就会被限流Blocked by Sentinel (flow limiting)
 *
 * 5.必须经过网关才能访问该接口/order/{orderId}
 * http://localhost:10010/order/101?authorization=admin
 */
@Component
public class HeaderOriginParser implements RequestOriginParser {

    @Override
    public String parseOrigin(HttpServletRequest request) {
        // 1.获取请求头
        String origin = request.getHeader("origin");
        // 2.非空判断
        if (StringUtils.isEmpty(origin)) {
            origin = "blank";
        }
        return origin;
    }
}
